package com.ankifyh.BujoTemplateGenerator;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CreateMarkdownActivity extends Activity {

    // 在类的开头添加
    private String generateIframe(String text) {
        return "[在线查询](https://m.baidu.com/s?word=" + text + ")|[百度百科查询](https://baike.baidu.com/search/word?word=" + text +")|[AI搜索](https://metaso.cn/?q=" + text + ")<iframe src=\"https://dict.eudic.net/mdicts/en/" + text + "\" width=\"100%\" height=\"300\" frameborder=\"0\" scrolling=\"yes\" style=\"border:none;\"></iframe><iframe src=\"s://" + text + "\" width=\"100%\" height=\"0\" frameborder=\"0\" scrolling=\"yes\" style=\"border:none;\"></iframe> #card #单词";
    }

    private void shareToEudic(String sharedText) {
    // 创建Uri对象，使用Eudic的Uri scheme和共享文本
    Uri uri = Uri.parse("eudic://peek/" + Uri.encode(sharedText));

    // 创建Intent
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查并请求写入外部存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                // 引导用户到设置页面开启权限
                Intent manageAllFilesIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);manageAllFilesIntent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(manageAllFilesIntent, Constants.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                return;
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        Constants.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                return;
            }
        }

        handleShareIntent(getIntent());
        finish(); // 保持finish()调用，使Activity在完成任务后结束
    }

    // 处理接收到的分享Intent
    private void handleShareIntent(Intent intent) {
        if (intent.getType() != null && intent.getType().startsWith("text/")) {
            String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
            if (sharedText != null) {
                String fileName = sanitizeFileName(sharedText + ".md");
                //查词
                shareToEudic(sharedText);
                // 使用共享文本作为文件名和内容
                writeToFileInRoot(generateIframe(sharedText), sharedText, fileName);
            }
        }
    }

     // 写入文件到根目录下的obseq/pages的方法
    private void writeToFileInRoot(String content, String sharedText, String fileName) {
        File obseqPagesDir = new File(Environment.getExternalStorageDirectory(), "obseq/pages");
        if (!obseqPagesDir.exists()) {
            obseqPagesDir.mkdirs();
        }

        if (obseqPagesDir.isDirectory()) {
            // 创建带分号的文件
            File semicolonFile = new File(obseqPagesDir, ";" + fileName);

            try (FileOutputStream fos = new FileOutputStream(semicolonFile, false)) {
                fos.write(content.getBytes(StandardCharsets.UTF_8)); // 使用UTF-8编码
                fos.flush();
                String message = "单词Page已写入";
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // 显示Toast消息
            } catch (IOException e) {
                e.printStackTrace();
                String errorMessage = "单词Page写入时发生错误: " + e.getMessage();
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show(); // 显示错误消息
            }


            // 无论带分号的文件是否存在，都尝试追加不带分号的文件
            File fileNameFile = new File(obseqPagesDir, fileName);

            String headerContent = "\n- ->[[;" + sharedText + "]]";

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileNameFile, true))) {
                writer.write(headerContent);

                writer.flush();
                String successMessage = "单词索引已成功追加到相应文件末尾。";
                Toast.makeText(this, successMessage, Toast.LENGTH_SHORT).show(); // 显示Toast消息
            } catch (IOException e) {
                e.printStackTrace();
                String errorMessage = "在相应文件末尾追加单词索引时发生错误: " + e.getMessage();
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show(); // 显示错误消息
            }


        } else {
            String message = "无法创建'obseq/pages'目录。";
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // 显示Toast消息
        }
    }


    // 清理文本，使用URL编码代替非法字符
    private String sanitizeFileName(String fileName) {
        // 定义非法字符列表
        String[] illegalChars = {"/", ":", "<", ">", "[", "]", "|", "\"", "\\", "*", "?"};

        // 遍历非法字符列表，使用URL编码替换
        for (String charToReplace : illegalChars) {
            fileName = fileName.replace(charToReplace, "%" + charToReplace.getBytes(StandardCharsets.UTF_8)[0]);
        }

        return fileName;
    }

    // 权限请求回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (resultCode == Activity.RESULT_OK) {
                // 用户已授权，继续处理文件操作
                handleShareIntent(getIntent());
            } else {
                // 用户未授权，可能需要提示用户并处理这种情况
                String message = "拒绝了外部存储读取权限。";
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // 显示Toast消息
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == Constants.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意了权限请求，可以在这里继续创建文件
                handleShareIntent(getIntent()); // 重新处理Intent
            } else {
                // 用户拒绝了权限请求，可能需要提示用户并处理这种情况
                String message = "拒绝了外部存储写入权限。";
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // 显示Toast消息
            }
        }
    }
}
